package com.pvdnc.riru.appinjector;

import android.annotation.SuppressLint;
import android.app.Application;
import android.util.Log;

import com.pvdnc.riru.appinjector.mirror.RActivityThread;
import com.pvdnc.riru.appinjector.mirror.RPackageManager;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class LoadablePackages {
    private static final String TAG=LoadablePackages.class.getSimpleName();

    private static final File sListFile=new File("/data/misc/riru/hook_pkgs.txt");

    public List<String> mHookPkgNameList=new ArrayList<>();

    public static void initPrivileged() throws IOException {
        if (!sListFile.exists()) {
            File parentFile=sListFile.getParentFile();
            Objects.requireNonNull(parentFile);

            if(!parentFile.exists()
            &&!parentFile.mkdirs())
                throw new IOException("fail to create riru's /data/misc dir");

            if (!sListFile.createNewFile()) {
                throw new IOException("fail to create hook pkg list file:" + sListFile);
            }
            FileUtils.write(sListFile, new LoadablePackages().toJson());
            Log.d(TAG, "hook pkg list file created");
        }
        sListFile.setWritable(true, false);
        sListFile.setReadable(true, false);

    }

    public LoadablePackages()  {

    }

    public String toJson(){
        return GsonUtils.toJson(this);
    }

    public static LoadablePackages fromFile() throws IOException {
        String json=FileUtils.readString(sListFile);
        return GsonUtils.fromJson(json,LoadablePackages.class);
    }

    @SuppressLint("WrongConstant")
    public static LoadablePackages fromPMS() {
        Application app= RActivityThread.currentApplication.call();
        String json= RPackageManager.getDefaultBrowserPackageName.call(app.getPackageManager(),
                Integer.MAX_VALUE);
        return GsonUtils.fromJson(json,LoadablePackages.class);
    }

    public boolean isHookable(String pkgName){
        boolean result= mHookPkgNameList.contains(pkgName);
        Log.d(TAG,"is pkg:"+pkgName+" hookable ? "+result);
        return result;
    }

    public boolean isHookable(){
        Application app=RActivityThread.currentApplication.call();
        return isHookable(app.getPackageName());
    }
}
